#include "StdAfx.h"
#include "MyEdit.h"

CMyEdit::CMyEdit(void)
: _precision( 0 )
{
}

CMyEdit::~CMyEdit(void)
{
}

BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
	//{{AFX_MSG_MAP(CMyEdit)
	ON_WM_CHAR()
	ON_WM_KEYDOWN()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


void CMyEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
	// TODO: Add your message handler code here and/or call default
	if( nChar == VK_RETURN )
	{
		GetParent()->SetFocus();
		return;
	}
	CEdit::OnChar(nChar, nRepCnt, nFlags);
}

void CMyEdit::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
	// TODO: Add your message handler code here and/or call default
	if( nChar == VK_RETURN )
	{
		GetParent()->SetFocus();
	}

	bool canDot = IsDot( nChar );
	CString content;
	GetWindowText( content );
	if(content.Find( L'.' ) != -1)
	{
		canDot = false;
	}

	if( IsNumber( nChar ) || IsFunction( nChar ) || canDot )
	{
		CEdit::OnKeyDown(nChar, nRepCnt, nFlags);
	}
}

bool CMyEdit::CanShow( UINT nChar )
{
	if( IsNumber( nChar ) || IsDot( nChar ) )
	{
		return true;
	}
	return false;
}

void CMyEdit::Show( UINT nChar, CRect pos )
{
	CString str;
	str.Format( L"%c", ConvertChar( nChar ) );
	Clear();
	SetWindowText( str );
	SetSel( 1, 1 );

	MoveWindow( pos );
	ShowWindow( SW_SHOW );
	SetFocus();
}

CString CMyEdit::GetText()
{
	CString strText;
	GetWindowText( strText );

	if( strText.GetLength() == 0 )
	{
		return L"";
	}

	double value = _wtof( strText );

	CString strFormat;
	strFormat.Format( L"%%.%df", _precision );

	CString strValue;
	strValue.Format( strFormat, value );
	return strValue;
}

UINT CMyEdit::ConvertChar( UINT nChar )
{
	switch ( nChar )
	{
	case 110:
	case 190:
		return '.';
	default:
		return nChar;
	}
}

bool CMyEdit::IsNumber( UINT nChar )
{
	return ( nChar >= '0' && nChar <= '9' ) || ( nChar >= VK_NUMPAD0 && nChar <= VK_NUMPAD9 );
}

bool CMyEdit::IsDot( UINT nChar )
{
	return nChar == 110 || nChar == 190;
}

bool CMyEdit::IsFunction( UINT nChar )
{
	return nChar == VK_BACK || nChar == VK_LEFT || nChar == VK_RIGHT || nChar == VK_DECIMAL;
}

void CMyEdit::SetPrecision( int precision )
{
	_precision = precision;
}